package job6.okHttp;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * okhttp封装
 */
@Slf4j
public class OkHttpUtil {

    private volatile static OkHttpUtil instance;

    /**
     * 具有重试机制的OkHttpClient
     */
    private OkHttpClient retryableOkHttpClient;

    private OkHttpUtil() {
        try {
            //如果发送失败，会重试3次，如果重试也都失败了，则一共会发送4次
            OkHttpRetryInterceptor okHttpRetryInterceptor = new OkHttpRetryInterceptor(3, 3000);
            OkHttpClient.Builder retryableBuilder = new OkHttpClient.Builder()
                    .retryOnConnectionFailure(true)
                    .addInterceptor(okHttpRetryInterceptor)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .connectTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS);
            retryableBuilder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            retryableOkHttpClient = retryableBuilder.build();
        } catch (Exception e) {
            log.error("retryableOkHttpClient 创建失败", e);
        }

    }

    /**
     * 单例模式
     *
     * @return
     */
    private synchronized static OkHttpUtil getInstance() {
        if (instance == null) {
            synchronized (OkHttpUtil.class) {
                if (instance == null) {
                    instance = new OkHttpUtil();
                }
            }
        }
        return instance;
    }

    /**
     * 构造get请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    private ResponseBody getRequest(String url, Map<String, String> headerMap) throws IOException {
        Request.Builder builder = new Request.Builder().addHeader("Connection", "close");
        if (headerMap != null && headerMap.size() > 0) {
            Iterator<String> it = headerMap.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                String value = headerMap.get(key);
                builder.addHeader(key, value);
            }
        }
        Request request = builder.url(url).build();
        Response response = retryableOkHttpClient.newCall(request).execute();
        return response.body();
    }


    /**
     * get请求
     *
     * @param url
     * @return String
     * @throws Exception
     */
    public static String get(String url) throws IOException {
        return getInstance().getRequest(url, null).string();
    }
}
